package com.lb.jwitter.service;

import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.jws.WebService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lb.jwitter.*;
import com.lb.jwitter.hibernate.*;
import com.lb.jwitter.util.ChumanoLogger;
import com.lb.jwitter.util.ConditionReport;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

@Service("tbl_ThongTin_HocVienService")
@Transactional
@WebService(endpointInterface = "com.lb.jwitter.service.Tbl_ThongTin_HocVienService")
public class Tbl_ThongTin_HocVienServiceImpl implements Tbl_ThongTin_HocVienService,Serializable {

   private Log log = LogFactory.getLog(Tbl_ThongTin_HocVienServiceImpl.class);
   private static final long serialVersionUID = -8740095022264495229L;

   @Autowired
   @Qualifier("tbl_ThongTin_HocVienDAO")
   private Tbl_ThongTin_HocVienDAO _tbl_ThongTin_HocVienDao;

   @Autowired
   @Qualifier("tbl_CTDT_KhoaDAO")
   private Tbl_CTDT_KhoaDAO _tbl_CTDT_KhoaDao;

   @Autowired
   @Qualifier("tbl_CTDT_HeDaoTaoDAO")
   private Tbl_CTDT_HeDaoTaoDAO _tbl_CTDT_HeDaoTaoDao;
   
   @Autowired
   @Qualifier("tbl_CTDT_ChuyenNganhDAO")
   private Tbl_CTDT_ChuyenNganhDAO _tbl_CTDT_ChuyenNganhDAO;

   public final List<Tbl_ThongTin_HocVien> findAlltbl_ThongTin_HocVien(int pageSize, int page){
   List<Tbl_ThongTin_HocVien> result = get_tbl_ThongTin_HocVienDao().findAll(pageSize, page);
       log.info("Number of user in DB:: "+result.size());
       return result;
   }

   @Transactional(noRollbackFor=IllegalArgumentException.class)
   public final Long createtbl_ThongTin_HocVien(Tbl_ThongTin_HocVien obj){
       return _tbl_ThongTin_HocVienDao.save(obj);
   }

   public final void updatetbl_ThongTin_HocVien(Tbl_ThongTin_HocVien obj){
       _tbl_ThongTin_HocVienDao.update(obj);
   }//end update methode

   public final Tbl_ThongTin_HocVien gettbl_ThongTin_HocVien (Long id){
       log.info("Try to retrieve the tbl_ThongTin_HocVien: "+id);
       return get_tbl_ThongTin_HocVienDao().get(id);
   }

   public void deletetbl_ThongTin_HocVien(Long id){
       log.info("Try to delete the tbl_ThongTin_HocVien by Id : "+ id);
       if(_tbl_ThongTin_HocVienDao.exists(id)){
	    _tbl_ThongTin_HocVienDao.delete(id);
       } else {
       	throw new IllegalArgumentException("EmployeeId '"+id+"' does not exists");
       }
   }

   public void deleteListtbl_ThongTin_HocVien(String[] listId){
       for(String id : listId){
   	    deletetbl_ThongTin_HocVien(Long.parseLong(id));
       }
   }

   public List<Tbl_ThongTin_HocVien> findtbl_ThongTin_HocVienByCondition(List<ConditionReport> cons,int pageSize,int page){ 
       return _tbl_ThongTin_HocVienDao.findByCondition(Tbl_ThongTin_HocVien.class, cons, pageSize, page); 
   } 
 
   public int counttbl_ThongTin_HocVienByCondition(List<ConditionReport> cons){ 
       return _tbl_ThongTin_HocVienDao.countByCondition(Tbl_ThongTin_HocVien.class, cons); 
   } 
 
   public final Tbl_ThongTin_HocVienDAO get_tbl_ThongTin_HocVienDao() {
   	return _tbl_ThongTin_HocVienDao;
   }
   public final void set_tbl_ThongTin_HocVienDao(Tbl_ThongTin_HocVienDAO obj) {
   	this._tbl_ThongTin_HocVienDao = obj;
   }

   public Tbl_CTDT_KhoaDAO get_tbl_CTDT_KhoaDao() {
       return _tbl_CTDT_KhoaDao;
   }
   public void set_tbl_CTDT_KhoaDao(Tbl_CTDT_KhoaDAO _tbl_CTDT_KhoaDao) {
       this._tbl_CTDT_KhoaDao = _tbl_CTDT_KhoaDao;
   }

   public Tbl_CTDT_HeDaoTaoDAO get_tbl_CTDT_HeDaoTaoDao() {
       return _tbl_CTDT_HeDaoTaoDao;
   }
   public void set_tbl_CTDT_HeDaoTaoDao(Tbl_CTDT_HeDaoTaoDAO _tbl_CTDT_HeDaoTaoDao) {
       this._tbl_CTDT_HeDaoTaoDao = _tbl_CTDT_HeDaoTaoDao;
   }
   
   public void createListtbl_ThongTin_HocVienByJSON(String data){
	   try{
		   ChumanoLogger.init(Tbl_ThongTin_HocVienServiceImpl.class.getName());
		   ChumanoLogger.log("0BAT DAU INSERT DU LIEU");
		   List<Tbl_ThongTin_HocVien> tbl_ThongTin_HocViens = new ArrayList<Tbl_ThongTin_HocVien>();

		   JSONArray jsons = (JSONArray) JSONSerializer.toJSON( data );
		   ArrayList<String> notChuyenNganhs = new ArrayList<String>();
		   ArrayList<String> notKhoas = new ArrayList<String>();
		   ArrayList<String> notHDTs = new ArrayList<String>();
			for(int i = 0; i < jsons.size() ; i++){
				JSONObject obj = jsons.getJSONObject(i);
				String logStr ="";
				//System.out.println("==============here0==================");
				//MSSV	HOTEN	NAMDAOVAO	MAKHOI	MAHEDAOTAO
				//MALOP	
				//EMAIL
				//-----------------Lay du lieu--------------------------
	        	//MSSV
				String mssv = obj.getString("MSSV");
				
				//1 HOTEN
				String hoten = obj.getString("HOTEN");
				
				//2 NAMDAOVAO
				int namdauvao = Integer.parseInt(obj.getString("NAMDAUVAO"));
				
				//----------------------------------------
				//3 MAKHOI
				//DHCKCDT07
				String maKhoi = obj.getString("MAKHOI");
				
				//ma nganh
				String machuyennganh = maKhoi.substring(4, 7);
				
				//nam
				String nam = maKhoi.substring(7, 9);
				
				Date now = new Date();
				int year = now.getYear() + 1900;
				String yearStr = year+"";

				nam = yearStr.substring(0, 2) + nam;
				
				int khoahoc = Integer.parseInt(nam);
				
				//khoa
				String makhoa =  maKhoi.substring(2, 4);
				
				//------------------------------------------
				//4 MAHEDAOTAO
				String mahdt = obj.getString("MAHEDAOTAO");
				
				//5 DIEMTBTL
				String lopHoc = obj.getString("MALOP");
				
				//6 EMAIL
				String email = null;
				try{
					email = obj.getString("EMAIL");
				}catch(Exception e){
					
				}
				 
				//7 TRANGTHAI
				//String trangthai = obj.getString("TRANGTHAI");
				
				logStr ="[ " + (i+1)+ " - " 
				+ "MSSV: " + mssv + " - " 
				+ "TEN: " + hoten + " - " 
				+ "NAMDAUVAO: " + namdauvao + " - " 
				+ "CN: " + machuyennganh + " - " 
				+ "KHOA: " + makhoa + " - " 
				+ "KHOAHOC: " + khoahoc + " - " 
				+ "HDT: " + mahdt + " - " 
				+ "MALOP: " + lopHoc + "]";
				
				//System.out.println("==============here1==================");
				//======================================================
				//Tim ChuyenNganh
				Tbl_CTDT_ChuyenNganh chuyennganh = new Tbl_CTDT_ChuyenNganh();
				List<Long> chuyennganhids = findChuyenNganhId(machuyennganh, makhoa);
				if(chuyennganhids==null || chuyennganhids.size()==0){
					ChumanoLogger.log(logStr + " NOT CN");
					if(!notChuyenNganhs.contains(machuyennganh)) notChuyenNganhs.add(machuyennganh);
					continue;
				}
				chuyennganh.setId(chuyennganhids.get(0));
				//System.out.println("==============here2==================");
				
				//Tim khoa
				Tbl_CTDT_Khoa khoa = new Tbl_CTDT_Khoa();
				List<Long> khoaids = findKhoaId(makhoa);
				if(khoaids==null || khoaids.size()==0){
					ChumanoLogger.log(logStr + " NOT KHOA");
					if(!notKhoas.contains(makhoa)) notKhoas.add(makhoa);
					continue;
				}
				khoa.setId(khoaids.get(0));
				//System.out.println("==============here3==================");
				
				//Tim Hedaotao
				Tbl_CTDT_HeDaoTao hdt = null;
				if(mahdt!=null &&!mahdt.equals("")){
					List<Long> hdtids = findHeDaoTaoId(mahdt);
					if(hdtids!=null && hdtids.size()>0){
						hdt = new Tbl_CTDT_HeDaoTao();
						hdt.setId(hdtids.get(0));
			        } else {
			        	logStr += " NOT HDT";
			        	if(!notHDTs.contains(mahdt)) notHDTs.add(mahdt);
			        }
				} else logStr += " NOT HDT_E";
				
				//System.out.println("==============here4==================");
				
				//------------------------------------------------------
				//======================================================
		        Tbl_ThongTin_HocVien hocvien = new Tbl_ThongTin_HocVien();
		        List<Long> ids = findHocVienId(mssv);
		        if(ids!=null && ids.size()>0){
		        	hocvien.setId(ids.get(0));
		        }
		        //System.out.println("==============here5==================");
		        
		        hocvien.setMSSV(mssv);
		        hocvien.setHoTen(hoten);
		        hocvien.setChuyenNganhId(chuyennganh);
		        hocvien.setHeDaoTaoId(hdt);
		        hocvien.setKhoaId(khoa);
		        hocvien.setKhoaHoc(khoahoc);
		        hocvien.setNamDauVao(namdauvao);
		        hocvien.setLopHoc(lopHoc);
		        hocvien.setEmail(email);
		        //hocvien.setTrangThai(trangthai);
		        
		        //System.out.println("------------LOG CHUMANO-------------");
		        //System.out.println("add " + i + ": " + mssv);
				//System.out.println("=================================");
				   
		        tbl_ThongTin_HocViens.add(hocvien); 
		        
		        ChumanoLogger.log(logStr);
			}//end for
			
			//-----------------------SAVE ALL --------------------
			_tbl_ThongTin_HocVienDao.saveOrUpdateAll(tbl_ThongTin_HocViens);
			
			ChumanoLogger.log("===================== not chuyen nganh=======================");
			reportArrayString(notChuyenNganhs);
			
			ChumanoLogger.log("===================== not khoa=======================");
			reportArrayString(notKhoas);
			
			ChumanoLogger.log("===================== not hedaotao=======================");
			reportArrayString(notHDTs);
		   }
		   catch (Exception e) {
			// TODO: handle exception
			   ChumanoLogger.log("ERROR: " +e.getMessage());
			   System.out.println("------------ERROR CHUMANO-------------");
			   e.printStackTrace();
			   System.out.println("=================================");
		   }
		   
		   ChumanoLogger.stop();
   }
   
   static void reportArrayString(ArrayList<String> arr){
		int i =1;
		for(String str :arr){
			ChumanoLogger.log(i + ". " + str);
			i++;
		}
	}
   private List<Long> findHocVienId(String mssv){
	   List<ConditionReport> cons = new ArrayList<ConditionReport>(); 
       {
       	 	ConditionReport con = new ConditionReport(); 
	       	con.setCol("MSSV");
	        con.setValue1(mssv);
	        con.setOperator("eq");
	        cons.add(con);	
       }
       List<String> columns = new ArrayList<String>();
       columns.add("id");
       
	   List<Long> hocvienId = _tbl_ThongTin_HocVienDao.findColumnByCondition(Tbl_ThongTin_HocVien.class,cons,columns, 1, 1);
	   return hocvienId;
   }
   
   private List<Long> findKhoaId(String ma){
	   List<ConditionReport> cons = new ArrayList<ConditionReport>(); 
       {
       	 	ConditionReport con = new ConditionReport(); 
	       	con.setCol("ma");
	        con.setValue1(ma);
	        con.setOperator("eq");
	        cons.add(con);	
       }
       List<String> columns = new ArrayList<String>();
       columns.add("id");
       
	   List<Long> ids = _tbl_CTDT_KhoaDao.findColumnByCondition(Tbl_CTDT_Khoa.class,cons,columns, 1, 1);
	   return ids;
   }
   
   private List<Long> findHeDaoTaoId(String ma){
	   List<ConditionReport> cons = new ArrayList<ConditionReport>(); 
       {
       	 	ConditionReport con = new ConditionReport(); 
	       	con.setCol("ma");
	        con.setValue1(ma);
	        con.setOperator("eq");
	        cons.add(con);	
       }
       List<String> columns = new ArrayList<String>();
       columns.add("id");
       
	   List<Long> ids = _tbl_CTDT_HeDaoTaoDao.findColumnByCondition(Tbl_CTDT_HeDaoTao.class,cons,columns, 1, 1);
	   return ids;
   }
   
   private List<Long> findChuyenNganhId(String ma,String maKhoa){
	   List<ConditionReport> cons = new ArrayList<ConditionReport>(); 
       {
       	 	ConditionReport con = new ConditionReport(); 
	       	con.setCol("ma");
	        con.setValue1(ma);
	        con.setOperator("eq");
	        cons.add(con);	
       }
       
       {
      	 	ConditionReport con = new ConditionReport(); 
	       	con.setCol("khoaId.ma");
	        con.setValue1(maKhoa);
	        con.setOperator("eq");
	        cons.add(con);	
      }
       List<String> columns = new ArrayList<String>();
       columns.add("id");
       
	   List<Long> ids = _tbl_CTDT_ChuyenNganhDAO.findColumnByCondition(Tbl_CTDT_ChuyenNganh.class,cons,columns, 1, 1);
	   return ids;
   }
}//endclass

